package com.spider.im.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
    private static final Logger logger = LoggerFactory.getLogger(SpringContextUtil.class);

    @Override
    public synchronized void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringContextUtil.applicationContext == null) {
            SpringContextUtil.applicationContext = applicationContext;
            logger.info("ApplicationContext initialized successfully.");
        } else {
            logger.warn("ApplicationContext is already initialized, ignoring the new context.");
        }
    }

    public static ApplicationContext getApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("Application Context is not initialized yet!");
        }
        return applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        if (applicationContext == null) {
            throw new IllegalStateException("Application Context is not initialized yet!");
        }
        return applicationContext.getBean(clazz);
    }

    public static Object getBean(String name) {
        if (applicationContext == null) {
            throw new IllegalStateException("Application Context is not initialized yet!");
        }
        return applicationContext.getBean(name);
    }
}
